package com.alogic.remote.xscript.util;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.jayway.jsonpath.JsonPath;
import org.apache.commons.lang3.StringUtils;

import java.util.Iterator;
import java.util.Map;

/**
 * 将当前文档的部分内容拷贝到主文档
 *
 * @author yyduan
 * @since 1.6.13.20 [20201016 duanyy]
 */
public class Copy2 extends AbstractLogiclet {

    protected String jsonPath;
    protected String tag = "";
    protected String masterId = "masterId";

    public Copy2(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        tag = PropertiesConstants.getRaw(p, "tag", tag);
        jsonPath = PropertiesConstants.getString(p, "path", jsonPath,true);
    }

    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        if (current instanceof JsonObject){
            XsObject json = ctx.getObject(masterId);
            if (json == null){
                throw new BaseException("core.e1001","It must be in a remote-as-json context,check your script.");
            }
            if (!(json instanceof JsonObject)){
                throw new BaseException("core.e1001","The master doc is not a JsonObject.");
            }

            @SuppressWarnings("unchecked")
            Map<String,Object> jsonNode = (Map<String,Object>)json.getContent();

            Object result = current.getContent();
            if (StringUtils.isNotEmpty(jsonPath)){
                result = JsonPath.read(result,jsonPath);
            }
            String tagValue = ctx.transform(tag);
            if (StringUtils.isNotEmpty(tagValue)){
                if (result != null){
                    jsonNode.put(tagValue,result);
                }
            }else{
                if (result instanceof Map<?,?>){
                    Map<String,Object> resultJson = (Map<String,Object>)result;
                    Iterator<Map.Entry<String,Object>> iter = resultJson.entrySet().iterator();
                    while (iter.hasNext()){
                        Map.Entry<String,Object> entry = iter.next();
                        jsonNode.put(entry.getKey(),entry.getValue());
                    }
                }
            }
        }else{
            throw new BaseException("core.not_supported",
                    String.format("Tag %s does not support protocol %s",this.getXmlTag(),root.getClass().getName()));
        }
    }
}
